//---------------------------------------------------------------------------
// this function extracts "Duration" and "fps" from an input video
// Youjie Zhou <zhou42@email.sc.edu>
//---------------------------------------------------------------------------
extern "C"
{
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
}
#include <mex.h>
//---------------------------------------------------------------------------
#define MAX_NAME 2048
char fileName[MAX_NAME];
//---------------------------------------------------------------------------
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
{
    if (nrhs!=1 && nlhs!=2)
    {
        mexPrintf("Usage: [len,fps] = %s(video)\n",mexFunctionName());
        return;
    }

    if (mxGetString(prhs[0],fileName,sizeof(fileName)-1))
        mexErrMsgTxt("Invalid file name.");
    
    av_register_all();

    AVFormatContext *Handle = NULL;
    if (avformat_open_input(&Handle,fileName,NULL,NULL))
        mexErrMsgTxt("Open video failed.");

    if (Handle->nb_streams==0)
    {
        avformat_close_input(&Handle);
        mexErrMsgTxt("Cannot find any streams in the video.\n");
    }

    plhs[0] = mxCreateDoubleMatrix(1,1,mxREAL);
    plhs[1] = mxCreateDoubleMatrix(1,1,mxREAL);

    double *len = mxGetPr(plhs[0]);
    double *fps = mxGetPr(plhs[1]);

    *len = Handle->duration / AV_TIME_BASE;
    *fps = av_q2d( Handle->streams[0]->avg_frame_rate );

    avformat_close_input(&Handle);
}
//---------------------------------------------------------------------------
